package com.pignest.hotel.ui.reception;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zkex.zul.Borderlayout;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Booking;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.definition.BookingStatus;
import com.pignest.hotel.global.picker.Receiver;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.ui.member.MemberPicker;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.UIUtils;

/**
 * 预订房间
 * */
public class AddBooking extends Borderlayout implements EventListener, Receiver<Member> {
	private static final long serialVersionUID = -7136276768539749174L;
	
	private static final String ACTION_READ_MEMBER_CARD = "member";
	
	private Textbox nameTextbox;
	private Textbox phoneTextbox;
	private Textbox memberTextbox;
	private Textbox remarkTextbox;
	private Datebox estimatedDatebox;
	private Listbox estimatedTimeListbox;
	private Listbox preserveListbox;
	private Label endTimeLabel;
	private BookingHistogram histogram;
	
	private Member member;

	public AddBooking() {
		addEventListener(Events.ON_CREATE, this);
	}
	
	public void booking() {
		String userName = nameTextbox.getValue();
		String phone = phoneTextbox.getValue();
		Date date = estimatedDatebox.getValue();
		String time =UIUtils.getSelectedValue(estimatedTimeListbox);
		String sPreserve=UIUtils.getSelectedValue(preserveListbox);
		String remark = remarkTextbox.getValue();
//		String sLiveDays = UIUtils.getSelectedValue(liveDays);
		List<String> rooms = histogram.getSelected();
		String result = addBooking(userName, phone, member, date, time, sPreserve, null, rooms, remark);
		if (result == null) {
			showResult("预订成功!");
			UIUtils.refresh();
		} else if (result.length() > 0) {
			showResult(result);
		}
	}
	
	public void calcTime() {
		Date date = estimatedDatebox.getValue();
		String time = UIUtils.getSelectedValue(estimatedTimeListbox);
		String sPreserve = UIUtils.getSelectedValue(preserveListbox);
		String endTime = calcTime(date, time, Integer.parseInt(sPreserve));
		endTimeLabel.setValue(endTime);
	}
	
	/** 
	 * 增加预订
	 * 
	 * @param userName 预订人
	 * @param phoneName 电话
	 * @param memberId 会员ID
	 * @param date 到达日期
	 * @param time 到达时间
	 * @param preserve 保留时间(分钟)
	 * @param roomIds 预留房间
	 * @return 错误说明, 为null表示没错
	 */
	private static String addBooking(String userName, String phone, Member member , Date date, 
			String time, String preserve, String liveDays, List<String> roomIds, String remark) {
	
	    if (StringUtils.isBlank(userName))
				return "用户名不能为空";
		if (StringUtils.isEmpty(phone))
				return "电话不能为空";
		
		if (date == null)
			return "请输入预订日期";
		date = DateUtil.parseDate(date, time);
		if (date.getTime() <= System.currentTimeMillis())
			return "选择的时间不合法:小于当前时间";

		int p = Utils.getInteger(preserve, 180);
		Date endTime = new Date(date.getTime() + p * 60 * 1000);
		
		//预订确认
		StringBuilder message = new StringBuilder();
		message.append("姓名: ").append(userName).append("\n");
		message.append("电话: ").append(phone).append("\n\n");
		if (member != null) {
			message.append("会员: ").append(member.getName()).append("\n\n");
		} else {
			message.append("普通非会员预订\n\n");
		}
		if (roomIds == null || roomIds.isEmpty()) {
			message.append("**不排房**\n\n");
		} else {
			message.append("预订客房 ").append(roomIds.size()).append(" 间.\n\n");
		}
		message.append("预抵时间: ").append(DateUtil.toString(date)).append("\n");
		message.append("保留时间: ").append(DateUtil.toString(endTime));
		try {
			if (Messagebox.YES != Messagebox.show(message.toString(), "预订确认", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION))
				return "";
		} catch (InterruptedException e) {
			return "";
		}
		Booking booking = new Booking();
		booking.setName(userName);
		booking.setPhone(phone);
		booking.setEstimatedTime(date);
		booking.setEndTime(endTime);
		booking.setMember(member);
		booking.setPreserve(p);
		booking.setTime(new Date());
		booking.setRemark(remark);
		booking.setStatus(BookingStatus.ONGOING.name());
		ReceptionService service = Services.getReceptionService();
//		int days = Utils.getInteger(liveDays, 1);
//		booking.setLeaveTime(new Date(date.getTime() + days * DateUtil.ONE_DAY));
		service.addBooking(booking, roomIds);
		return null;
	}
	
	public void onUser(Object data) {
		if (!(data instanceof String[])) {
			showResult("数据错误");
			return;
		}
		String[] strs = (String[])data;
		String action = strs[0];
		if (ACTION_READ_MEMBER_CARD.equals(action)) {
			String serial = strs[1];
			Card card = Services.getCardService().getCardBySerialNumber(serial);
			if (card == null || !card.isEnable()) {
				showResult("无效卡");
				return;
			}
			if (card.getType() != Card.TYPE_MEMBER) {
				showResult("不是会员卡");
				return;
			}
			Member m = Services.getMemberService().getMemberByCardNumber(card.getCardNumber());
			if (m == null) {
				showResult("无效会员卡");
				return;
			}
			onPicked(m);
		}
	}
	
	private void showResult(String str) {
		UIUtils.alert(str);
	}
	
	/**
	 * 计算时间(预订时间 -> 失效时间)
	 * */
	private static String calcTime(Date date, String hms, int delay) {
		if (date == null || hms == null || delay <= 0)
			return null;
		Date d = DateUtil.parseDate(date, hms);
		return DateUtil.toString(new Date(d.getTime() + delay * 60L * 1000), "yyyy-MM-dd HH:mm");
	}
	
	public void onPickMember() {
		MemberPicker.pickMember(this);
	}
	
	@Override
	public Member getPicked() {
		return member;
	}

	@Override
	public void onPicked(Member o) {
		this.member = o;
		memberTextbox.setValue(o == null ? null : o.getDisplayName());
		nameTextbox.setValue(o == null ? null : o.getName());
		phoneTextbox.setValue(o == null ? null : o.getMobile());
	}

	@Override
	public void onEvent(Event event) throws Exception {
		if (Events.ON_CREATE.equals(event.getName())) {
			nameTextbox = (Textbox)getFellow("userName");
			phoneTextbox = (Textbox)getFellow("phoneNumber");
			memberTextbox = (Textbox)getFellow("member");
			remarkTextbox = (Textbox)getFellow("remark");
			estimatedDatebox = (Datebox)getFellow("estimatedDate");
			estimatedTimeListbox = (Listbox)getFellow("estimatedTime");
			preserveListbox = (Listbox)getFellow("preserve");
			endTimeLabel = (Label)getFellow("endTime");
			histogram = (BookingHistogram)getFellow("roomHistogram");
			
			estimatedDatebox.setValue(new Date());
			calcTime();
		}
	}
	
}
